import axios from 'axios'
import { Message } from 'element-ui'
import session from './session'
import router from '../router/index.js'

const service = axios.create({
  // baseURL:  process.env.NODE_ENV == 'producton' ? process.env.VUE_APP_BASE_API: '', // url = base url + request url
  baseURL: "http://192.168.3.4:9000/", // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000 // request timeout
  timeout: 600000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if(session.get('token')) {
      config.headers.token = session.get('token')
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {

    var res = response.data
    let code = res.code
    if (code) {
      // 将code强转为Number类型 (要提前)
      code = Number(res.code)
    }
    // 判断是否登录
    if(code == 5001) {
      router.push('/login')
    }
    if (code && code !== 0) {
      if(res.msg) {
        // 全局弹窗。显示异常信息
        Message({
            message: res.msg,
            type: 'error',
            duration: 2 * 1000
        })
      }  
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
        // 全局弹窗。显示成功（有msg才弹窗，一般查询接口都不会返回msg，增删改才会返回msg）
        if(res.msg) {
          Message({
              message: res.msg || '操作成功',
              type: 'success',
              duration: 2 * 1000
          })
        }
        
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error || 'Error',
      type: 'error',
      duration: 2 * 1000
  })
    return Promise.reject(error)
  }
)

export default service
